# encoding: utf-8
import random
import time
import string
import threading
import tap_config
from sys_utils import execute_cmd_line, LOG

# 使用thread来完成周期采样流量功能
class FlowTrafficCollectionThread(threading.Thread):

    def __init__(self, thread_id, thread_name, handler_manager):
        threading.Thread.__init__(self)
        self.thread_id = thread_id
        self.thread_name = thread_name
        self.handler_manager = handler_manager
        self.data_container = handler_manager.data_container

    def collect_traffic_info(self):
        LOG("Traffic collection round.")
        for flow_id in self.data_container.get_monitored_flowentries():
            target_flow = self.data_container.get_flowentry(flow_id)
            curr_traffic = self.collect_flow_info(flow_id)
            curr_traffic['target_flow_id'] = flow_id
            last_traffic = target_flow.last_flow_traffic()
            if not last_traffic:
                curr_traffic['flow_speed'] = 0
                print "C1=", curr_traffic['flow_speed']
            else:
                bytesent = curr_traffic.get('flow_bytes') - last_traffic.get('flow_bytes')
                speed = bytesent / float(tap_config.traffic_interval)
                #curr_traffic['flow_speed'] = speed
                curr_traffic['flow_speed'] = random.randint(10, 200)
                print "C2=", curr_traffic['flow_speed']
            curr_traffic['flow_speed'] = random.randint(10, 200)
            target_flow.offer_flow_traffic(curr_traffic)

    def collect_flow_info(self, flow_id):
        params = {}
        params['ofctl'] = tap_config.ofctl
        params['br_name'] = tap_config.bridge_name
        params['flow_id'] = flow_id
        cmd_line = tap_config.GET_FLOW_ENTRY_BY_ID_CMD.substitute(params)
        status, result, error = execute_cmd_line(cmd_line)
        if status == -1:
            return None
        else:
            return self.parse_flow_info_result(result)

    def parse_flow_info_result(self, result):
        '''
        cookie=0x0, duration=1634.538s, table=0, n_packets=n/a, n_bytes=0, ip,in_port=13,nw_src=59.66.0.0/16 actions=output:15
        '''
        lines = result.split('\n')
        if len(lines) <= 1:
            return None

        infos = {}
        parts = lines[1].split(',')
        for part in parts:
            str = string.strip(part)
            if str[0:9] == 'n_packets':
                pkt = 0
                pkt_str = str.split('=')[1]
                if pkt_str != 'n/a':
                    pkt = int(pkt_str)
                infos['flow_packets'] = pkt
            if str[0:7] == 'n_bytes':
                bytes_str = str.split('=')[1]
                bytes = int(bytes_str)
                infos['flow_bytes'] = bytes

        return infos

    def run(self):
        LOG("FlowTrafficCollectionThread has started.")
        while True:
            self.collect_traffic_info()
            time.sleep(tap_config.traffic_interval)